package com.sunjy.demo1.controller;

import com.sunjy.common.annotation.BeanValid;
import com.sunjy.common.base.BaseController;
import com.sunjy.common.domain.ApiResponseT;
import com.sunjy.common.domain.HeaderEnum;
import com.sunjy.demo1.form.UserForm;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: sunjy
 * @Date: 2018/10/18 17:39
 * @Description:
 */
@RestController
@RequestMapping("redssion")
@Slf4j
public class TestRedssionController extends BaseController {

    @Autowired
    private RedissonClient redissonClient;

    @BeanValid
    @PostMapping(value="/lock1", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResponseT lock1(@Valid @RequestBody UserForm user, BindingResult bind) {
        RLock fairLock =redissonClient.getFairLock("anyLock");

        // 尝试加锁，最多等待100秒，上锁以后10秒自动解锁
        try {
            boolean res = fairLock.tryLock(10, 10, TimeUnit.SECONDS);
            if(res){
                System.out.println("lock1获得锁");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            fairLock.unlock();
        }
        return ApiResponseT.success();
    }
    @BeanValid
    @PostMapping(value="/lock2", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResponseT lock2(@Valid @RequestBody UserForm user, BindingResult bind) {
        RLock fairLock =redissonClient.getFairLock("anyLock");

        // 尝试加锁，最多等待100秒，上锁以后10秒自动解锁
        try {
            boolean res = fairLock.tryLock(10, 100, TimeUnit.SECONDS);
            System.out.println("lock2获取锁失败");
            if(res){
                System.out.println("lock2获得锁");
            }
            Thread.sleep(100000);
        } catch (InterruptedException e) {
            log.info("获取锁失败->{}",e);
            return ApiResponseT.error(HeaderEnum.RESSSION_LOCK);
        }finally {
            fairLock.unlock();
            System.out.println("lock2释放锁");
        }
        return ApiResponseT.success();
    }
}
